package com.baimsg.reader.thread

import com.baimsg.reader.bean.BookBean
import com.baimsg.reader.bean.Portions
import com.baimsg.reader.network.ApiInterface
import com.baimsg.reader.util.Log
import com.baimsg.reader.util.extension.appendPath
import com.baimsg.reader.util.extension.write
import org.jsoup.Jsoup
import java.io.File

/**
 * Create by Baimsg on 2022/3/21
 *
 **/
class TaskThread(
    private val index: Int,
    private var outPath: File,
    private val bookInfo: BookBean,
    private val portions: Portions
) : Runnable {

    override fun run() {
        val str = ApiInterface.getArticleContent(bookInfo.id, portions.id, portions.bigContentId)?.msg
        if (str.isNullOrBlank()) {
            Log.e("${bookInfo.title} [序号：$index] -> error")
            return
        }
        val document = Jsoup.parse(str)
        val chapters = document.select(".j-chapter").select(".section")
        val contents = document.select("p.section")
        val sb = StringBuilder()
        var title: String? = null
        chapters.forEachIndexed { index, element ->
            if (index == 0) title = element.text()
            sb.append(element.text() + "\n")
        }
        contents.forEach {
            sb.append(it.text() + "\n")
        }
        outPath.appendPath("${index}-${title}.txt").write(sb)
        Log.d("$title -> [序号:$index] cache end")
    }
}